#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
int ticket = 20;
pthread_mutex_t mutex;
void* routine(void* arg)
{
	char* id = (char*)arg;
	while(1)
	{
		pthread_mutex_lock(&mutex);
		if(ticket > 0)
		{
			printf("%s sell ticket:%d\n",arg,ticket);
			ticket--;
			pthread_mutex_unlock(&mutex);
			usleep(100000);
		}
		else
		{
			pthread_mutex_unlock(&mutex);
			break;
		}
	}
	return NULL;
}
int main()
{
	pthread_mutex_init(&mutex,NULL);

	pthread_t t1,t2,t3,t4;
	pthread_create(&t1,NULL,routine,"Thread 1");
	pthread_create(&t2,NULL,routine,"Thread 2");
	pthread_create(&t3,NULL,routine,"Thread 3");
	pthread_create(&t4,NULL,routine,"Thread 4");

	pthread_join(t1,NULL);
	pthread_join(t2,NULL);
	pthread_join(t3,NULL);
	pthread_join(t4,NULL);
	
	pthread_mutex_destroy(&mutex);
	return 0;
}


